package org.ning.http;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.ning.model.TagResult;

import java.io.IOException;
import java.net.URI;
import java.net.URL;
import java.util.stream.Stream;

/**
 * @author WangNing
 * @version 1.0
 * @date 2020/7/5 11:19
 */
public class HttpUtils {

    private  static HttpUtils instance = null;

    private static final String TAG_URL_FORMAT = "https://hub.docker.com/v2/repositories/library/%s/tags/?page_size=20&page=%d";

    private HttpClientContext clientContext = null;
    private  HttpClient httpClient = null;


    private HttpUtils(){

        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
        clientContext = new HttpClientContext();
        CookieStore cookieStore = new BasicCookieStore();
        clientContext.setCookieStore(cookieStore);
        httpClient = HttpClients.custom().setConnectionManager(cm).build();

    }

    public static HttpUtils getInstance(){
        if( instance != null){
            return instance;
        }
        synchronized (HttpUtils.class){
            if(instance!=null){
                return instance;
            }
            instance = new HttpUtils();
            return instance;
        }
    }


    public  TagResult getAllTags(String library, int page){
        HttpGet get = new HttpGet(String.format(TAG_URL_FORMAT, library, page));
        try{
            HttpResponse response = httpClient.execute(get, clientContext);
            String result = EntityUtils.toString(response.getEntity());
            EntityUtils.consume(response.getEntity());
            JSONObject object = JSON.parseObject(result);
            TagResult tagResult = TagResult.parseFromJson(object, library);
            tagResult.setCurrentPage(page);
            return tagResult;
        }catch (IOException e){
            System.err.println("网络异常");
            System.exit(-1);
        }
        return null;
    }


}
